public class Sort {

    /**
     * 选择排序
     * @param array
     */
    public void selectSort(int[] array) {
         for (int i = 0; i < array.length; i++) {
             int minIndex = i;
             for (int j = i + 1; j < array.length; j++) {
                 if (array[j] < array[minIndex]) {
                     minIndex = j;
                 }

             }
             int temp = array[i];
             array[i] = array[minIndex];
             array[minIndex] = temp;
         }
    }

    public void heapSort(int[] array) {
        createHeap(array);
        int end = array.length - 1;
        while (end > 0) {
            int temp = array[end];
            array[end] = array[0];
            array[0] = temp;
            shiftDown(array, 0, end);
            end--;
        }
    }

    private void createHeap(int[] array) {
        for (int parent = (array.length - 1 -1) / 2; parent >= 0; parent--) {
            shiftDown(array, parent, array.length);
        }
    }

    private void shiftDown(int[] array, int parent, int length) {
        int child = 2 * parent + 1;
        while (child < length) {
            if (child + 1 < length && array[child] < array[child + 1]) {
                child = child + 1;
            }
            if (array[parent] < array[child]) {
                int temp = array[parent];
                array[parent] = array[child];
                array[child] = temp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    public void bubbleSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {5, 3, 8, 6, 2, 7, 1, 4};
        Sort sort = new Sort();
        sort.bubbleSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
    
    
}
